import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_utils/api_service/acg_service.dart';
import 'package:xvideos/hj_utils/api_service/search_service.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../home_cell_style/video_simple_cell_widget.dart';

abstract class SearchHotTableLogic extends GetxController  {
  final int type;

  SearchHotTableLogic(this.type);

  RefreshController? controller;

  final dataArr = [];
  int page = 1;

  List<int> typeArr = [0, 1, 2];

  bool isLoading = true;

  /// 默认为视频
  double childRatio = 191 / 174;
  int crossAxisCount = 2;
  double spaceH = 7.w;
  double spaceV = 12.h;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    fetchPageData();
  }

  @override
  disposeCustomController() {}

  fetchPageData({bool isRefresh = true});

  Widget instanceChildItem(int index);

}

class VideoHotController extends SearchHotTableLogic {
  VideoHotController(super.type);
  @override
  fetchPageData({bool isRefresh = true}) async {
    if (isRefresh) {
      page = 1;
    }
    final res = await SearchService.getSearchHotVideos(page, 12, type);
    isLoading = false;
    if (isRefresh) {
      dataArr.clear();
      controller?.refreshCompleted();
    }
    if (res?.hasNext ?? false) {
      controller?.loadComplete();
    } else {
      controller?.loadNoData();
    }
    dataArr.addAll(res?.videos ?? []);
    page += 1;
    update();
  }

  @override
  Widget instanceChildItem(int index) {
    return VideoSimpleCellWidget(videoModel: dataArr[index]);
  }
}

class ACGHotController extends SearchHotTableLogic {
  ACGHotController(super.type);
  @override
  double get childRatio => 126 / 244;
  @override
  double get spaceH => 7.w;
  @override
  double get spaceV => 14.h;
  @override
  int get crossAxisCount => 3;
  @override
  fetchPageData({bool isRefresh = true}) async {
    if (isRefresh) {
      page = 1;
    }
    final res = await ACGService.fetchAcgRecommend(page, 12, type: type);
    isLoading = false;
    if (isRefresh) {
      dataArr.clear();
      controller?.refreshCompleted();
    }
    if (res?.hasNext ?? false) {
      controller?.loadComplete();
    } else {
      controller?.loadNoData();
    }
    dataArr.addAll(res?.list ?? []);
    page += 1;
    update();
  }

  @override
  Widget instanceChildItem(int index) {
    return Container();
  }
}

T instanceController<T>(int type) {
  final t = T.toString();
  if (t == 'VideoHotController') return VideoHotController(type) as T;
  if (t == 'ACGHotController') return ACGHotController(type) as T;

  throw '$t 没有实现';
}
